using zhwy.saas.api.Entity.Sys;
using zhwy.saas.api.Extensions.Log;
using zhwy.saas.api.Repository;
using zhwy.saas.api.Services.Sinterface.Sys;

namespace zhwy.saas.api.Services.Sys
{
    /// <summary>
    /// 系统权限服务实现
    /// </summary>
    public class SysPermissionService : BaseService<PermissionsEntity>, ISysPermissionService
    {
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="repository">权限仓储接口</param>
        /// <param name="logger">日志服务</param>
        public SysPermissionService(IBaseRepository<PermissionsEntity> repository, ILogExt logger)
            : base(repository, logger)
        {
        }

        /// <summary>
        /// 获取角色的所有权限
        /// </summary>
        /// <param name="roleId">角色ID</param>
        /// <returns>权限列表</returns>
        public async Task<List<PermissionsEntity>> GetPermissionsByRoleIdAsync(long roleId)
        {
            // TODO: 实现根据角色ID查询权限列表
            return await _repository.GetListAsync(p => p.Status == 1);
        }

        /// <summary>
        /// 获取用户的所有权限
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <returns>权限列表</returns>
        public async Task<List<PermissionsEntity>> GetPermissionsByUserIdAsync(long userId)
        {
            // TODO: 实现根据用户ID查询权限列表，需要关联角色表
            return await _repository.GetListAsync(p => p.Status == 1);
        }

        /// <summary>
        /// 获取菜单的所有权限
        /// </summary>
        /// <param name="permcodes">权限编码</param>
        /// <returns>权限列表</returns>
        public async Task<List<PermissionsEntity>> GetPermissionsByPermcodesAsync(List<string> permcodes)
        {
            // TODO: 实现根据权限编码查询权限列表
            return await _repository.GetListAsync(p => permcodes.Contains(p.Perm_code) && p.Status == 1);
        }

        /// <summary>
        /// 批量保存权限
        /// </summary>
        /// <param name="permissions">权限列表</param>
        /// <returns>是否保存成功</returns>
        public async Task<bool> SavePermissionsAsync(List<PermissionsEntity> permissions)
        {
            try
            {
                // TODO: 实现批量保存权限的逻辑
                foreach (var permission in permissions)
                {
                    if (permission.Id > 0)
                    {
                        await _repository.UpdateAsync(permission);
                    }
                    else
                    {
                        await _repository.AddAsync(permission);
                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                _logger.Error(ex, "批量保存权限失败");
                return false;
            }
        }
    }
}